<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="活动名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <router-link v-hasPermi="['ypp:activity:add']" :to="{path:'/zx/activity/edit'}" class="link-type">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          v-hasPermi="['ypp:activity:add']"
        >新增</el-button>
        </router-link>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ypp:activity:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warn"
          icon="el-icon-delete"
          size="mini"
          :disabled="single"
          @click="handleCancel"
          v-hasPermi="['ypp:activity:remove']"
        >取消</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ypp:activity:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ypp:activity:export']"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="activityList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="ID" align="center" prop="id" />-->
<!--      <el-table-column label="活动编码" align="center" prop="code" :show-overflow-tooltip="true" />-->
      <el-table-column label="活动名称" align="center" prop="name" width="150px">
        <template slot-scope="scope">
          <el-button type="text" style="white-space: pre-wrap" @click="showGenerations(scope.row)">{{scope.row.name}}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="活动类型" align="center" prop="typeName"  />
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" />
<!--      <el-table-column label="报名时间" align="center" prop="startTime" :show-overflow-tooltip="true">-->
<!--        <template slot-scope="scope">-->
<!--          <span >{{ scope.row.startTime  }} - {{ scope.row.activityEndTime }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="活动时间" align="center" prop="endTime" :show-overflow-tooltip="true">-->
<!--        <template slot-scope="scope">-->
<!--          <span >{{ scope.row.activityStartTime  }} - {{ scope.row.endTime }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="活动每期人数" align="center" prop="maleTotal"/>
      <el-table-column label="报名费用" align="center" prop="fee">
        <template slot-scope="scope">
          <span style="color: #000000;cursor: pointer;" >{{ scope.row.fee?scope.row.fee:'免费' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动报名人数" align="center" prop="maleNum">
        <template slot-scope="scope">
          <span style="color: #000000;cursor: pointer;" @click="getUserList(scope.row.id,2000)">{{ scope.row.num }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="已确认" align="center" prop="confirm">-->
<!--        <template slot-scope="scope">-->
<!--         <span style="color: #0000ff;cursor: pointer;" @click="getUserList(scope.row.id,200)">{{ scope.row.confirm }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="未确认" align="center" prop="notConfirm">-->
<!--        <template slot-scope="scope">-->
<!--          <span style="color: #ff0000;cursor: pointer;" @click="getUserList(scope.row.id,300)">{{ scope.row.maleNum-scope.row.confirm }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="已签到" align="center" prop="sign">
        <template slot-scope="scope">
          <span style="color: #0000ff;cursor: pointer;"  @click="getUserList(scope.row.id,400)">{{ scope.row.sign }}</span>
        </template>
      </el-table-column>
      <el-table-column label="未签到" align="center" prop="notSign">
        <template slot-scope="scope">
          <span style="color: #ff0000;cursor: pointer;"  @click="getUserList(scope.row.id,500)">{{ scope.row.confirm-scope.row.sign }}</span>
        </template>
      </el-table-column>
      <el-table-column label="已签退" align="center" prop="signOff">
        <template slot-scope="scope">
          <span style="color: #0000ff;cursor: pointer;"  @click="getUserList(scope.row.id,10)">{{ scope.row.signOff }}</span>
        </template>
      </el-table-column>
      <el-table-column label="未签退" align="center" prop="notSignOff">
        <template slot-scope="scope">
          <span style="color: #ff0000;cursor: pointer;"  @click="getUserList(scope.row.id,700)">{{ scope.row.sign-scope.row.signOff }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort">
        <template slot-scope="scope">
          <el-input-number
            v-model="scope.row.sort"
            placeholder="请输入排序"
            clearable
            size="small"
            style="width: 90px"
            @change="change(scope.row)"
          />
        </template>

      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini"
                     type="text"
                     icon="el-icon-view" @click="handlePreview(scope.row)">查看二维码</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['ypp:activity:edit']"
            >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ypp:activity:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改活动项目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="内容">
          <Editor v-model="form.content" className="ypp_activity_editor"/>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer" style="margin-top: 20px">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="preview.title" :visible.sync="preview.open" width="500px" append-to-body>
    <el-descriptions :column="1" :title="preview.name">
      <el-descriptions-item style="text-align:center;" label="签到二维码">
        <div  v-for="(item,index) in preview.src" :key="index" style="text-align: center;margin-bottom: 20px;" >
          <el-image :src="base_url+item" style="width: 300px" :title="item.substring(item.indexOf('/qrcode/')+8)" :alt="item.substring(item.indexOf('/qrcode/')+8)"/>
          <div>{{ item.substring(item.indexOf('/qrcode/')+8) }}</div>
        </div>
      </el-descriptions-item>
    </el-descriptions>
      <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="gen">重新生成</el-button>
      <el-button @click="previewClose">关 闭</el-button>
    </div>
    </el-dialog>
    <el-dialog title="档期列表" :visible.sync="showActivityGenerations" width="1000px" append-to-body>
      <el-table :data="activityGenerations" >
        <el-table-column prop="name" align="center" label="档期名称"/>
        <el-table-column prop="signEndTime" align="center" label="报名截止时间"/>
        <el-table-column prop="activityStartTime" align="center" label="活动开始时间"/>
        <el-table-column prop="activityEndTime" align="center" label="活动结束时间"/>
        <el-table-column prop="last" align="center" label="剩余名额">
          <template slot-scope="scope">
            <span>{{ scope.row.last }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="count" align="center" label="报名人数">
          <template slot-scope="scope">
            <span @click="getUserList(scope.row.activityId,2000,scope.row.id)" style="cursor: pointer">{{ scope.row.count }}</span>
          </template>
        </el-table-column>

      </el-table>
    </el-dialog>
    <el-dialog title="使用人列表" :visible.sync="userOpen" width="500px" append-to-body>
      <el-table :data="userList" >
        <el-table-column prop="name" align="center" label="营员"/>
        <el-table-column prop="phone" align="center" label="监护人电话"/>
        <el-table-column v-if="showTime === 2" prop="signTime" align="center" label="签到时间"/>
        <el-table-column v-if="showTime === 1" prop="signOffTime" align="center" label="签退时间"/>
      </el-table>
    </el-dialog>
    <el-dialog title="选择档期" :visible.sync="generationShow" width="300px" append-to-body>
      <el-form>
        <el-form-item label="档期" prop="generationId">
          <el-select v-model="generationId" :value="generationId" placeholder="请选择档期" clearable size="small">
            <el-option v-for="(item,index) in generationList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer" style="margin-top: 20px">
        <el-button type="primary" @click="cancelGeneration">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listActivityDetail,statusList, getActivity,cancelActivity, delActivity, addActivity, updateActivity, exportActivity, genActivitySign } from "@/api/ypp/activity";
  import {listGeneration} from "../../../api/ypp/generation";
  import { listDept } from "@/api/system/dept";
  import { checkRole } from "@/utils/permission.js";
  import Editor from '@/components/Editor';

  export default {
    name: "Activity1",
    components: {
      Editor
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 活动项目表格数据
        activityList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 状态字典
        statusOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          name: undefined,
          status: undefined,
          deptId: undefined
        },
        // 表单参数
        form: {
          name: [
            { required: true, message: "活动名称不能为空", trigger: "blur" }
          ]
        },
        // 表单校验
        rules: {
        },
        deptOptions:[],
        preview:{
          open:false,
          // title:'签到二维码',
          name:'',
          src:'',
        },
        id: undefined,
        base_url: process.env.VUE_APP_BASE_API,
        userList:[],
        userOpen:false,
        isSubmit:false,
        showTime:0,
        generationShow:false,
        generationList:[],
        generationId:undefined,
        activityGenerations:[],
        showActivityGenerations:false
      };
    },
    created() {
      if (checkRole(['admin'])){
        listDept().then(response => {
          this.deptOptions = response.data;
        });
      }

      this.getDicts("ypp_activity_status").then(response => {
        this.statusOptions = response.data;
      });
      this.getList();
    },
    watch: {
      $route(to, from) {
        //当参数改变时就会触发比方法，以此达到数据属性
        this.getList();
      }
    },
    methods: {
      showGenerations(row){
        listGeneration({activityId:row.id}).then(res=>{
          if(res.code == 200){
            this.activityGenerations = res.rows;
            this.activityGenerations.map(function(item,index){
              item.last = row.maleTotal-item.count;
            });
            this.showActivityGenerations = true;
          }
        })
      },
      change(item){
        updateActivity(item).then(res=>{
          if(res.code === 200){
            this.$message.success("修改成功")
          }
        })
      },
      getUserList(activityId,status,generationId){
        if(status == 10 ){
          this.showTime = 1;
        }else if(status == 400){
          this.showTime = 2;
        }else{
          this.showTime = 0;
        }
        statusList(activityId,status,generationId).then(res =>{
          this.userList = res.rows;
          this.userOpen = true;
        })
      },
      /** 查询活动项目列表 */
      getList() {
        this.loading = true;
        listActivityDetail(this.queryParams).then(response => {
          this.activityList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      typeFormat(row,column){
        if(row.type == 1){
          return "个人"
        }else if(row.type == 0){
          return "企业"
        }
        return "未知"
      },
      // 状态字典翻译
      statusFormat(row, column) {
        return this.selectDictLabel(this.statusOptions, row.status);
      },
      deptFormat(row,column){
        var txt = '';
        this.deptOptions.filter(e =>{
          if (e.deptId == row.deptId){
            txt = e.deptName;
            return;
          }
        })
        return txt;
      },
      handleCheckRole(v){
        return checkRole([v]);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          name: undefined,
          delFlag: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          status: "1",
          deptId: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!=1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加活动项目";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        this.$router.push("/zx/activity/edit?id="+id)
        // getActivity(id).then(response => {
        //   this.form = response.data;
        //   this.open = true;
        //   this.title = "修改活动项目";
        // });
      },
      //查看二维码
      handlePreview(row){
        var list = [];
        this.id = row.id;
        const id = row.id;
        getActivity(id).then(response => {
          var d = response.data;
          this.preview.name = d.name;

          if (d.signCodePath == null || d.signCodePath===''){
            genActivitySign(id).then(res => {
              if(res.data){
                list = res.data.split(",");
                this.preview.open = true;
              }else{
                this.preview.open = true;
              }
              this.preview.src = list;
            })
          } else {
            this.preview.src = d.signCodePath.split(",");
            this.preview.open = true;
          }
        });
      },
      checkComment(row){
        this.$router.push("/ypp/comment?id="+row.id)
      },
      gen(){
        let loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        genActivitySign(this.id).then(res => {
          console.log(res)
          if(res.data){
            this.preview.src = res.data.split(",");
            loading.close();
          }else{
            loading.close();
          }

        })
      },
      previewClose(){
        this.preview.open = false;
      },
      /** 提交按钮 */
      submitForm: function() {
        if(this.isSubmit){
          return;
        }
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.isSubmit = true;
            if (this.form.id != undefined) {
              updateActivity(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                  this.isSubmit = false;
                }
              });
            } else {
              addActivity(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                  this.isSubmit = false;
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除活动项目编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delActivity(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
      },
      /** 取消按钮操作 */
      handleCancel(row) {
        var that = this;
        const id = row.id || this.ids;
        console.log(id[0])
        var a ;
        getActivity(id[0]).then(res=>{
          if(res.code === 200){
            a = res.data;
            if(a && a.yppActivityGenerations&&a.yppActivityGenerations.length>0) {
              that.generationList = a.yppActivityGenerations;
              that.generationShow = true;
            }else{
              that.$message.error("该活动没有可选档期");
            }
          }
        })
      },
      cancelGeneration(){
        this.generationShow = false;
        var id = this.generationId;
        this.$confirm('是否取消活动项目编号为"' + id + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return cancelActivity(id);
        }).then(() => {
          this.getList();
          this.msgSuccess("取消成功");
        }).catch(function() {});
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有活动项目数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportActivity(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
      }
    }
  };
</script>
<!-- 全局样式 -->
<style>
  .ypp_activity_editor{
    height: 400px;
  }
</style>
